/*
*	Copyright(c) 2020 lutianming email：641471957@qq.com
*
*	Sheeps may be copied only under the terms of the GNU Affero General Public License v3.0
*/

#include "lsheepsrun.h"
#include "stdio.h"
#include "stdlib.h"
#include "LuaProtocol.h"
#include "luavms.h"
#include "common.h"

#ifdef __WINDOWS__
#ifdef _DEBUG
#ifndef _WIN64
#pragma comment(lib,"..\\Win32\\sheeps\\Debug\\framework.lib")
#pragma comment(lib,"..\\Win32\\sheeps\\Debug\\lua.lib")
#pragma comment(lib,"..\\Win32\\sheeps\\Debug\\lua_3rd.lib")
#else
#pragma comment(lib, "..\\X64\\sheeps\\Debug\\framework.lib")
#pragma comment(lib, "..\\X64\\sheeps\\Debug\\lua.lib")
#pragma comment(lib, "..\\X64\\sheeps\\Debug\\lua_3rd.lib")
#endif // _WIN32
#else
#ifndef _WIN64
#pragma comment(lib, "..\\Win32\\sheeps\\Release\\framework.lib")
#pragma comment(lib, "..\\Win32\\sheeps\\Release\\lua.lib")
#pragma comment(lib, "..\\Win32\\sheeps\\Release\\lua_3rd.lib")
#else
#pragma comment(lib, "..\\X64\\sheeps\\Release\\framework.lib")
#pragma comment(lib, "..\\X64\\sheeps\\Release\\lua.lib")
#pragma comment(lib, "..\\X64\\sheeps\\Release\\lua_3rd.lib")
#endif // _WIN32
#endif
#else
#include <unistd.h>
#endif // __WINDOWS__

static void LuaTaskStart(hClientTaskConfig task) {
	config_init(config_lua);
}

static void LuaTaskStop(hClientTaskConfig task) {}

static ReplayProtocol* LuaCreateUser(void) {
	LuaProtocol* hdl = new LuaProtocol();
	return hdl;
}

int __STDCALL SheepsLuaTest(const char* file) 
{
	int state;
	lua_State* L = create_lua_State();
	if (!file) return 0;
	state = luaL_dofile(L, file);
	if (state != LUA_OK)
	{
		const char* msg = lua_tostring(L, -1);
		printf("sheeps: %s\n", msg);
		lua_close(L);
		return -1;
	}
	return 0;
}

int __STDCALL TaskManagerRunWithLua(int project_id, const char* group_id, bool server, const char* ip, int port, const char* configfile, const char* scriptfile)
{
	char project_config[256] = { 0x0 };
	char project_script[256] = { 0x0 };
	projectid = project_id;
	if (scriptfile)
		main_lua = scriptfile;
	else {
		snprintf(project_script, sizeof(project_script), "project/lua/%d/script/main.lua", projectid);
		main_lua = project_script;
	}
	if (configfile)
		config_lua = configfile;
	else {
		snprintf(project_config, sizeof(project_config), "project/lua/%d/config.ini", projectid);
		config_lua = project_config;
	}
	snprintf(TaskAgentInfoString, sizeof(TaskAgentInfoString), "配置：[%s]\n脚本：[%s]\n", config_lua, main_lua);

	task_agent_welcome_set("欢迎使用SuperSheeps for lua5.4.2");
	TaskManagerRun(projectid, group_id, server, ip, port, init_luavms, NULL, LuaCreateUser, LuaTaskStart, LuaTaskStop);
	return 0;
}
